#include "msgApp.h"
#include "helper.h"
#include "commdef.h"
#include "msgManager.h"
#include "resource.h"
#include "maiwindow.h"

TMsgApp::TMsgApp( HINSTANCE hInstance, LPSTR cmdLine, int cmdShow )
: TApp( hInstance, cmdLine, cmdShow )
{
	LoadLibrary( "RICHED20.DLL" );
	srand( (UINT)Time() );
	TLibInit_AdvAPI32();
	TLibInit_Crypt32();
}

TMsgApp::~TMsgApp()
{

}

void TMsgApp::InitWindow()
{
	const char seprater = ' ';
	int portNum = atoi( _cmdLine );
	if( portNum == 0 )
		portNum = IPMSG_DEFAULT_PORT;

	ULONG nicAddr = 0;
	char* p = NULL;
	char* tok = strchr( _cmdLine, '/' );
	if( tok && separate_token( tok, seprater, &p ) )
	{
		bool diag = true;
		DWORD status = 0xffffffff;

		if( _stricmp( tok, "/NIC" ) == 0 )
		{
			if( tok = separate_token( NULL, seprater, &p ) )
				nicAddr = ResolveAddr( tok );
		}
		else if( _stricmp( tok, "/MSG" ) == 0 )
		{
			MsgManager msgMng( nicAddr, portNum );
			ULONG command = IPMSG_SENDMSG | IPMSG_NOADDLISTOPT | IPMSG_NOLOGOPT;
			
			while( ( tok = separate_token( NULL, seprater, &p ) ) != NULL && *tok == '/' )
			{
				if( _stricmp( tok, "/LOG" ) == 0 )
					command &= ~IPMSG_NOLOGOPT;
				else if( _stricmp( tok, "/SEAL" ) == 0 )
					command &= IPMSG_SECRETOPT;
			}

			char* msg = separate_token( NULL, 0, &p );
			if( msg )
			{
				diag = false;
				ULONG destAddr = ResolveAddr( tok );
				if( destAddr != NULL )
					status = msgMng.Send( destAddr, htons( portNum ), command, msg ) ? 0 : -1;
			}
		}
		if( nicAddr == 0 )
		{
			if( diag )
				MessageBox( 0, "ipmsg.exe [portNum] [/MSG [/LOG] [/SEAL] <hostname or IP addr> \
<message>]\r\nipmsg.exe [portNum] [/NIC nicAddr]", MSG_STR, MB_OK );
			::ExitProcess( status );
			return;
		}
	}

	char	className[MAX_PATH_U8] = IPMSG_CLASS;
	if( portNum != IPMSG_DEFAULT_PORT || nicAddr )
		wsprintf( className, nicAddr ? "%s_%d_%s" : "%s_%d", IPMSG_CLASS, portNum, 
		inet_ntoa(*(in_addr*)&nicAddr ) );

	HANDLE hMutex = ::CreateMutex( NULL, FALSE, className );
	::WaitForSingleObject( hMutex, INFINITE );

	HWND hWnd = FindWindowU8( className );
	if( hWnd != NULL || TRegisterClass( className, CS_DBLCLKS, ::LoadIcon( _hInstance, (LPCSTR)IPMSG_ICON ),
		::LoadCursor( NULL, IDC_ARROW ) ) == 0 )
	{
		if( hWnd != NULL ) ::SetForegroundWindow( hWnd );
		::ExitProcess( 0xffffffff );
		return;
	}
	
	_mainWnd = new TMainWin( nicAddr, portNum );
	_mainWnd->Create( className, IP_MSG, WS_OVERLAPPEDWINDOW | (IsNewShell() ? WS_MINIMIZE : 0 ) );
	::ReleaseMutex( hMutex );
	::CloseHandle( hMutex );
	//::ShowWindow( _mainWnd->_hWnd, SW_SHOWNORMAL );
}